#include <iostream>
#include <string>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h> //还有htons
#include <unistd.h>
#include <thread>


void Usage(const std::string& proc) //使用手册
{
    std::cout << std::endl;
    std::cout << "Usage: " << proc << " serve_ip serve_prot" << std::endl;
    std::cout << std::endl; 
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    
    //如果正确输入，那么开始通信
    //先提取，ip和port
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    //填写服务端字段
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    //server.sin_addr.s_addr = inet_addr(serverip.c_str()); //inet_addr有线程安全问题
    inet_aton(serverip.c_str(), &(server.sin_addr));
    socklen_t len = sizeof(server);

    //创建 socket fd
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cout << "socker error" << std::endl;
        return 1;
    }
    
    //多线程使用，一个receive线程，一个respond线程
    std::thread receive_td([sockfd](){
        char buffer[1024] = { 0 };
        while (true)
        {
            struct sockaddr_in temp;
            socklen_t temp_len = sizeof(temp);

            ssize_t ret_recv = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&temp, &temp_len);
            if(ret_recv > 0)
            {
                buffer[ret_recv] = 0;
                std::cerr << buffer << std::endl; //用标准错误流进行打印
                              //用一个终端作为消息的接受
            }
        }
    }); //接受信息的线程

    std::thread respond_td([sockfd, &server, len](){
        std::string message;
        while(true)
        {
            std::cout << "please enter@ "; 
            getline(std::cin, message); //获取信息 —> 阻塞等待输入
        
            int ret_sd = sendto(sockfd, message.c_str(), message.size(), 0, (const struct sockaddr*)&server, len);
            if(ret_sd < 0)
            {
                perror("sendto");
                continue;
            }
        }

    }); //发送信息的线程

    receive_td.join();
    respond_td.join();
    
    close(sockfd);
    return 0;
}